<?php
// Database Configuration
$host = "localhost";
$username = "root";
$password = "";
$database = "library";

try {
    $conn = new PDO("mysql:host=$host;dbname=$database", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// Create Database and Table
function setupDatabase($conn)
{
    $sql = "CREATE TABLE IF NOT EXISTS books (
        id INT AUTO_INCREMENT PRIMARY KEY,
        title VARCHAR(255) NOT NULL,
        author VARCHAR(255) NOT NULL,
        isbn VARCHAR(20) NOT NULL,
        publishedDate DATE NOT NULL
    )";
    $conn->exec($sql);
}
setupDatabase($conn);

// Handle Requests
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'];

    if ($action === 'add') {
        $title = $_POST['title'];
        $author = $_POST['author'];
        $isbn = $_POST['isbn'];
        $publishedDate = $_POST['publishedDate'];

        $stmt = $conn->prepare("INSERT INTO books (title, author, isbn, publishedDate) VALUES (?, ?, ?, ?)");
        $stmt->execute([$title, $author, $isbn, $publishedDate]);
    }

    if ($action === 'edit') {
        $id = $_POST['id'];
        $title = $_POST['title'];
        $author = $_POST['author'];
        $isbn = $_POST['isbn'];
        $publishedDate = $_POST['publishedDate'];

        $stmt = $conn->prepare("UPDATE books SET title = ?, author = ?, isbn = ?, publishedDate = ? WHERE id = ?");
        $stmt->execute([$title, $author, $isbn, $publishedDate, $id]);
    }

    if ($action === 'delete') {
        $id = $_POST['id'];

        $stmt = $conn->prepare("DELETE FROM books WHERE id = ?");
        $stmt->execute([$id]);
    }
}

// Fetch Data
$stmt = $conn->query("SELECT * FROM books");
$books = $stmt->fetchAll(PDO::FETCH_ASSOC);
